package les.anagrama;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import les.anagrama.util.Dictionary;
import les.anagrama.util.Level;
import les.anagrama.util.Ranking;
import les.anagrama.util.Score;
import les.anagrama.util.Word;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Play extends Activity {
	private Word word;
	private List<Character> anagram;
	private List<String> solved;
	private ArrayAdapter<String> solvedAdapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.play);

		selectWord();
		fillWordView();
		startChronometer();
	}

	private void shareIt() {
		int score = getScore();
		Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
		sharingIntent.setType("text/plain");
		String shareBody = "Eu fiz " + score + " no AnaGrama! Tente você também!";
		sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
		startActivity(Intent.createChooser(sharingIntent, "Share via"));
	}
	
	public void next(View view) {
		LinearLayout wordView = (LinearLayout) findViewById(R.id.play_word);
		wordView.removeAllViews();
		LinearLayout anagramView = (LinearLayout) findViewById(R.id.play_anagram);
		anagramView.removeAllViews();

		selectWord();
		fillWordView();
	}

	public void save(View view) {
		Chronometer chronometer = (Chronometer) findViewById(R.id.play_chronometer);
		chronometer.stop();
		final int score = getScore();

		final Dialog dialog = new Dialog(this);
		dialog.setContentView(R.layout.play_save);
		dialog.setTitle("Salvar pontuação atual");

		TextView text = (TextView) dialog.findViewById(R.id.play_score);
		text.setText("Pontuação: " + score);

		WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
		lp.copyFrom(dialog.getWindow().getAttributes());
		lp.width = WindowManager.LayoutParams.FILL_PARENT;
		lp.height = WindowManager.LayoutParams.FILL_PARENT;

		ImageButton sharingButton = (ImageButton) dialog.findViewById(R.id.buttonTwitter);
		sharingButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				shareIt();
			}
		});
		
		Button botaoSalvar = (Button) dialog
				.findViewById(R.id.play_save_confirm);

		botaoSalvar.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				saveScore(new Score(getPlayerName(), score, (Level) getIntent()
						.getExtras().getSerializable("level")));
				dialog.dismiss();
				finish();
			}

			private String getPlayerName() {
				EditText playerName = (EditText) dialog
						.findViewById(R.id.play_save_name);
				String name = playerName.getText().toString();
				if (name == null || name.trim().length() == 0) {
					return "PLAYER";
				} else {
					return name;
				}
			}
		});

		dialog.show();
		dialog.getWindow().setAttributes(lp);
	}

	private void startChronometer() {
		Chronometer chronometer = (Chronometer) findViewById(R.id.play_chronometer);
		chronometer.start();
	}

	private int getScore() {
		Chronometer chronometer = (Chronometer) findViewById(R.id.play_chronometer);
		long elapsed = SystemClock.elapsedRealtime() - chronometer.getBase();
		return (int) (solved.size() * word.getWord().length() * 1000000 / elapsed);
	}

	private void saveScore(Score score) {
		Ranking ranking = new Ranking(this);
		if (ranking.addScore(score)) {
			Toast.makeText(this, "Novo Recorde!", Toast.LENGTH_LONG).show();
		} else {

			Toast.makeText(this, "Pontos insuficientes para entrar no ranking", Toast.LENGTH_LONG).show();
		}
	}

	private void updateCounter() {
		TextView counter = (TextView) findViewById(R.id.play_counter);
		counter.setText(String.format("%d/%d", solved.size(),
				word.getAnagrams()));
	}

	private void selectWord() {
		word = Dictionary.getInstance(this).getWord(
				(Level) getIntent().getExtras().getSerializable("level"));

		anagram = new LinkedList<Character>() {
			private static final long serialVersionUID = 1L;

			@Override
			public String toString() {
				String str = "";
				for (Character ch : this) {
					str += ch;
				}
				return str;
			}
		};

		solved = new LinkedList<String>();
		solvedAdapter = new ArrayAdapter<String>(this, R.layout.play_solved,
				solved);
		ListView solvedView = (ListView) findViewById(R.id.play_solved);
		solvedView.setAdapter(solvedAdapter);

		updateCounter();
	}

	private void fillWordView() {
		List<Character> chars = new ArrayList<Character>(word.getWord()
				.length());
		for (int i = 0; i < word.getWord().length(); i++) {
			chars.add(word.getWord().charAt(i));
		}
		Collections.shuffle(chars);

		LinearLayout wordView = (LinearLayout) findViewById(R.id.play_word);
		for (Character ch : chars) {
			Button btn = new Button(this);
			btn.setText(ch.toString());
			btn.setOnClickListener(new PickChar());
			wordView.addView(btn);
		}
	}

	private void pickChar(Button btn) {
		LinearLayout wordView = (LinearLayout) findViewById(R.id.play_word);
		final LinearLayout anagramView = (LinearLayout) findViewById(R.id.play_anagram);

		btn.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				discardChar((Button) view);
			}
		});

		wordView.removeView(btn);
		if (anagramView.getChildCount() > 0) {
			anagramView.getChildAt(anagramView.getChildCount() - 1).setEnabled(
					false);
		}
		anagramView.addView(btn);

		this.anagram.add(btn.getText().charAt(0));
		if (this.anagram.size() == word.getWord().length()) {
			if (Dictionary.getInstance(this).contains(
					new Word(anagram.toString(), 0, word.getLevel()))
					&& !solved.contains(anagram.toString())) {
				solved.add(anagram.toString());
				updateCounter();
				solvedAdapter.notifyDataSetChanged();

				if (solved.size() == word.getAnagrams()) {
					save(btn);
				}
			}

			anagram.clear();
			anagramView.removeAllViews();
			fillWordView();
		}
	}

	private void discardChar(Button btn) {
		LinearLayout wordView = (LinearLayout) findViewById(R.id.play_word);
		final LinearLayout anagramView = (LinearLayout) findViewById(R.id.play_anagram);

		btn.setOnClickListener(new PickChar());

		anagramView.removeView(btn);
		if (anagramView.getChildCount() > 0) {
			anagramView.getChildAt(anagramView.getChildCount() - 1).setEnabled(
					true);
		}
		wordView.addView(btn);

		this.anagram.remove(this.anagram.size() - 1);
	}

	private class PickChar implements OnClickListener {
		public void onClick(View view) {
			pickChar((Button) view);
		}
	}
}
